package behaviors;

import model.Assets;
import model.Entity;
import model.Factory;

import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.contacts.ContactPoint;
import org.jbox2d.dynamics.contacts.ContactResult;
import org.newdawn.slick.Input;

import controller.Global;

public class Gun extends Behavior {

	@Override
	public void update(Body b) {
		super.update(b);

		if (Global.input.isKeyDown(Input.KEY_SPACE)
				&& body.getPosition().y > Global.waterLevel) {

			Vec2 v, f;
			Entity e = Assets.getInstance().getEntity(
					"assets/entities/bullet.txt");
			int sign = 1;

			if (((Entity) body.getUserData()).facing) {
				sign = -1;
			}

			float power = sign * 500f;

			if (((Entity) body.getUserData()).type == Entity.CIRCLE) {
				sign *= ((Entity) body.getUserData()).radius * 2f;
			} else {
				sign *= ((Entity) body.getUserData()).sizeX * 2f;
			}

			v = new Vec2(body.getPosition().x, body.getPosition().y);
			f = new Vec2((float) (power * Math.cos(body.getAngle())),
					(float) (power * Math.sin(body.getAngle())));

			e.x = v.x + (float) (sign * Math.cos(body.getAngle()));
			e.y = v.y + (float) (sign * Math.sin(body.getAngle()));
			e.timeToDie = System.currentTimeMillis() + 500;
			Factory.createEntity(e).applyForce(f, v);
			Assets.getInstance().getSound("assets/sfx/ricochet.wav").play(5,
					0.5f);
		}
	}

	@Override
	public void onCollide(ContactPoint arg0) {
	}

	@Override
	public void onPersist(ContactPoint arg0) {
	}

	@Override
	public void onRemove(ContactPoint arg0) {
	}

	@Override
	public void onResult(ContactResult arg0) {
	}

	@Override
	public void init() {
	}
}
